#include<stdio.h>
#include<Winsock2.h>
#include<process.h>
#include<String.h>
#include<conio.h>
#include<windows.h>
#define TRUE 1
#pragma comment(lib,"ws2_32.lib")

    SOCKET S;


void recvMess(void*);

//Set text Color
void color(const unsigned short color1)
{        
        if(color1>=0&&color1<=15)
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color1);
        
    else
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}

int main(){
    //initialize DLL
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2),&wsaData);

    //Create Socket
    SOCKET Server=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    //Setup SocketAddress
    struct sockaddr_in ServerAddr;
    ServerAddr.sin_family=AF_INET;
    ServerAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
    ServerAddr.sin_port=htons(8080);
    //Bind Socket 
    bind(Server,(SOCKADDR*)&ServerAddr,sizeof(SOCKADDR));

    //Listening Socket 
    listen(Server,5);
    int nSize=sizeof(SOCKADDR);

    //Accept Client Link
    SOCKET SERVER=accept(Server,(SOCKADDR*)&ServerAddr,&nSize);
    S=SERVER;

    //Start a new Thread to handel Message receive
    _beginthread(recvMess,0,NULL);


    //Send message to Client
    char *str;
    char String[512];
    
    while(TRUE){
        
        gets(String);
        str=String;
        send(SERVER,str,strlen(str)+sizeof(char),0);
        memset(String,0,sizeof(String));
        
        

    }


    //Discontinue the use of DLL and Close Socket
    closesocket(Server);
    closesocket(SERVER);
    closesocket(S);
    WSACleanup();
    return 0;
}


 //A method to Receive Data
 void recvMess(void *args){
     
     char Buffer[512]={""};
     while(TRUE){
         memset(Buffer,0,sizeof(Buffer));
         recv(S,Buffer,512,0);
         if(Buffer != ""){
             color(9);
             printf("%s\n",Buffer);
             color(7);
            }
        } 
     
        
     
     _endthread();
    }
